var map;
var game;

var selectedItem;
var infowindow;
var geocoder;

var selectedCity;
var selectedLatitude;
var selectedLongitude;
var selectedOnClickAction;

/**
 * Paths to item images
 */

var coinImage = '${COIN_IMG}';
var questionImage = '${QUESTION_IMG}';
var bonusImage = '${BONUS_IMG}';

var createURL = '${CREATE_URL}';

var viewURL = '${VIEW_URL}';

$(document).ready(function() {
	game = new Game();
	$('#addCoinButton').removeAttr('disabled');
	$('#addQuestionButton').removeAttr('disabled');
	$('#addBonusButton').attr('disabled', true);
	/**
	 * Map initialization
	 */
	geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(43.380126326682316, -8.392455154418936);
	var myOptions = {
		zoom: 12,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControl: true,
		navigationControl: true,
		navigationControlOptions: {
			style: google.maps.NavigationControlStyle.ZOOM_PAN,
			position: google.maps.ControlPosition.LEFT
		},
	}
	map = new google.maps.Map(document.getElementById('mapCanvas'), myOptions);
	google.maps.event.addListener(map, 'click', function(event) {
   		doOnClick(event);
	});
	infowindow = new google.maps.InfoWindow({
		disableAutoPan : true
	});
});
function doOnClick(event) {
	if (selectedOnClickAction != null) {
		selectedOnClickAction(event);
	}
}
function selectOnClickAction(action) {
	selectedOnClickAction = action;
}
function changeCityClicked() {
	$('#citySpan').html('click anywhere on map');
	$('#latitudeSpan').html('?');
	$('#longitudeSpan').html('?');				
	$('#showCityOptions').hide();
	elements = $('.gameLocationInfoSpan');
	elements.removeClass('gameLocationInfoSpan');
	elements.addClass('gameLocationInfoSpanGrey');
	selectOnClickAction(showCityOptions);
}
function showCityOptions(event) {
	if (geocoder) {
		geocoder.geocode({'latLng': event.latLng}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				if (results[1]) {
					$('#cityOptionsDiv').html('');
					$('#cityOptionsDiv').append('<span id="cityOptionsNote">We found some posible city names. Please select the one you want to be displayed: </span><br/>');
					selectedLatitude = event.latLng.lat();
					selectedLongitude = event.latLng.lng();
					for (var i in results[1].address_components) {
						$('#cityOptionsDiv').append('<input id="selectedCityId_' + i + '" type="radio" onclick="selectCity(' + i + ')" value="' + results[1].address_components[i].long_name + '"/><span>' + results[1].address_components[i].long_name + '</span><br/>');
					}
				}
			} else {
				elements = $('.gameLocationInfoSpanGrey');
				elements.removeClass('gameLocationInfoSpanGrey');
				elements.addClass('gameLocationInfoSpan');
				alert('Geocoder failed due to: ' + status);
				$('#cityLabel').html(game.city);
			}
		});
	}
	else {
		elements = $('.gameLocationInfoSpanGrey');
		elements.removeClass('gameLocationInfoSpanGrey');
		elements.addClass('gameLocationInfoSpan');
		$('#cityLabel').html(game.city);
	}
}
function selectCity(index) {
	city = $('#selectedCityId_' + index).val();
	$('#citySpan').html(city);
	$('#latitudeSpan').html(selectedLatitude.toFixed(6));
	$('#longitudeSpan').html(selectedLongitude.toFixed(6));
	game.city = city;
	game.latitude = selectedLatitude;
	game.longitude = selectedLongitude;
	elements = $('.gameLocationInfoSpanGrey');
	elements.removeClass('gameLocationInfoSpanGrey');
	elements.addClass('gameLocationInfoSpan');
	$('#showCityOptions').show();
	$('#cityOptionsDiv').html('');
	selectOnClickAction();
}
function addCoin(event) {
	id = game.items.length + 1;
	marker = placeMarker(event.latLng, id, coinImage);	
	var item = new Coin(id,
		10,
		marker);
	game.items[game.items.length] = item;
	refreshItemsList();
	selectItem(item);
}
function addQuestion(event) {
	id = game.items.length + 1;
	marker = placeMarker(event.latLng, id, questionImage);
	var item = new Question(id,
		10, 
		marker);
	item.associatedBonuses = new Array();
	game.items[game.items.length] = item;
	refreshItemsList();
	selectItem(item);
	selectOnClickAction();
	$('#addBonusButton').removeAttr('disabled');
}
function onAttachBonusClick(event) {
	$('#addBonusButton').attr('disabled', true);
	selectOnClickAction(addBonus);
}
function addBonus(event) {
	id = game.items.length + 1;
	marker = placeMarker(event.latLng, id, bonusImage);
	var item = new Bonus(id,
		10, 
		marker,
		selectedItem);
	selectedItem.associatedBonuses[selectedItem.associatedBonuses.length] = item;
	game.items[game.items.length] = item;
	refreshItemsList();
	selectItem(selectedItem);
	selectOnClickAction();
	$('#addBonusButton').removeAttr('disabled');
	$('#addCoinButton').removeAttr("disabled");
	$('#addQuestionButton').removeAttr("disabled");
}
function placeMarker(position, itemId, image) {
	var marker = new google.maps.Marker({
		position : position, 
		draggable : true,
		map : map,
		clickable : true,
		icon : image,
	});
	google.maps.event.addListener(marker, 'click', function() {
		selectItem(getItem(game.items, itemId));
	});
	google.maps.event.addListener(marker, 'dragstart', function() {
		item = getItem(game.items, itemId);
		$('#row_' + itemId).html(getUneditableRowContentHtml(item));
	});
	google.maps.event.addListener(marker, 'drag', function() {
		$('#lat_' + itemId).html(marker.position.lat().toFixed(6));
		$('#lng_' + itemId).html(marker.position.lng().toFixed(6));
	});
	google.maps.event.addListener(marker, 'dragend', function() {
	});
	return marker;
}
function refreshItemsList() {
	$('.itemRow').remove();
	for (var i in game.items) {
		if (game.items[i] != null) {
			addItemToList(game.items[i]);
		}
	}
}
function getEditableRowContentHtml(item) {
	return '<td onclick="selectItemById(' + item.id + ')">' + item.id + '</td>' +
		'<td onclick="selectItemById(' + item.id + ')"><div class="itemIcon"><img src="' + item.marker.icon +'"/></div></td>' +
		'<td onclick="selectItemById(' + item.id + ')"><input id="points_' + item.id + '" type="text" maxlength="6" class="itemInput" value="' + item.points +'"/></td>' +
		'<td onclick="selectItemById(' + item.id + ')"><input id="lat_' + item.id + '" type="text" maxlength="8" class="itemInput" value="' + item.marker.position.lat().toFixed(6) +'"/></td>' +
		'<td onclick="selectItemById(' + item.id + ')"><input id="lng_' + item.id + '" type="text" maxlength="8" class="itemInput" value="' + item.marker.position.lng().toFixed(6) +'"/></td>' +
		'<td><div id="deleteItem_' + item.id + '" class="littleLink"><a href="#" onclick="deleteItem(' + item.id + ')">delete</a></div></td>' + 
		'<td><div id="saveItem_' + item.id + '" class="littleLink"><a href="#" onclick="saveItem(' + item.id + ')">save</a></div></td>';
}
function getUneditableRowContentHtml(item) {
	return '<td onclick="selectItemById(' + item.id + ')">' + item.id + '</td>' +
		'<td onclick="selectItemById(' + item.id + ')"><div class="itemIcon"><img src="' + item.marker.icon +'"/></div></td>' +
		'<td onclick="selectItemById(' + item.id + ')" id="points_' + item.id + '"><span class="itemInfo">' + item.points +'</td>' +
		'<td onclick="selectItemById(' + item.id + ')"><span id="lat_' + item.id + '" class="itemInfo">' + item.marker.position.lat().toFixed(6) +'</td>' +
		'<td onclick="selectItemById(' + item.id + ')"><span id="lng_' + item.id + '" class="itemInfo">' + item.marker.position.lng().toFixed(6) +'</td>' +
		'<td><div id="deleteItem_' + item.id + '" class="littleLink"><a href="#" onclick="deleteItem(' + item.id + ')">delete</a></div></td>' + 
		'<td><div id="editItem_' + item.id + '" class="littleLink"><a href="#" onclick="editItem(' + item.id + ')">edit</a></div></td>';
}
function addItemToList(item) {
	$('#itemsTable').append(
		'<tr class="itemRow unselected" id="row_' + item.id + '">' +
		getUneditableRowContentHtml(item) + '</tr>');
}
function doDeleteItem(id) {
	var item = getItem(game.items, id);

	if (item instanceof Question) {
		for (var i in item.associatedBonuses) {
			if (item.associatedBonuses[i] != null) {
				doDeleteItem(item.associatedBonuses[i].id);
				item.associatedBonuses[i] = null;
			}
		}
		$('#addBonusButton').attr("disabled", true);
		$('#addCoinButton').removeAttr("disabled");
		$('#addQuestionButton').removeAttr("disabled");
	}
	else if (item instanceof Bonus) {
		for (var i in item.associatedQuestion.associatedBonuses) {
			if (item.associatedQuestion.associatedBonuses[i] != null && 
				item.associatedQuestion.associatedBonuses[i].id == item.id) {
				item.associatedQuestion.associatedBonuses[i] = null;
			}
		}
	}
	item.marker.setMap(null);
	for (var i in game.items) {
	if (game.items[i] != null && game.items[i].id == item.id) {
			game.items[i] = null;
		}
	}
	item = null;
}
function deleteItem(id) {
	if (confirm('Are you sure?')) {
		doDeleteItem(id);
		refreshItemsList();
	}
}
function editItem(id) {
	item = getItem(game.items, id);
	$('#points_' + id).val(item.points);
	$('#row_' + id).html(getEditableRowContentHtml(item));
	$('#points_' + id).focus();
	for (var i in game.items) {
		if ($('#editItem_' + game.items[i].id) != null) {
			$('#editItem_' + game.items[i].id + ' a').hide();
		}
	}
}
function saveItem(id) {
	item = getItem(game.items, id);
	item.points = $('#points_' + id).val();
	$('#row_' + id).html(getUneditableRowContentHtml(item));
	for (var i in game.items) {
		if ($('#editItem_' + game.items[i].id) != null) {
			$('#editItem_' + game.items[i].id + ' a').show();
		}
	}
}
/**
 * Returns the item associated to a marker
 */
function getItem(items, id) {
	return jQuery.grep(items, function(n, i) {
		if (n != null) {
			return n.id == id;
		}
	})[0];
}
function getLastQuestion() {
	var questions = jQuery.grep(game.items, function(n, i) {
		var result;
		if (n != null && n instanceof Question) {
			return n;
		}
	});
	return questions[questions.length - 1];
}
function selectItemById(itemId) {
	selectItem(getItem(game.items, itemId));
}
function selectItem(item) {
	content = 'Points : ' + item.points;
	infowindow.setContent(content);
    infowindow.open(map, item.marker);
	var elements = $('.itemRow');
	elements.removeClass();
	elements.addClass('itemRow');
	elements.addClass('unselected');
	
	selectedItem = item;
	$('#row_' + selectedItem.id).addClass('selected');
	if (item instanceof Question) {
		$('#questionInfo').show();
		$('#addCoinButton').attr('disabled', true);
		$('#addQuestionButton').attr('disabled', true);
		for (var i in selectedItem.getAssociatedBonuses()) {
			$('#row_' + item.getAssociatedBonuses()[i].id).addClass('associatedBonus');
		}
	}
	else {
		if (item instanceof Bonus) {
			$('#row_' + item.associatedQuestion.id).addClass('associatedQuestion');
		}
		$('#questionInfo').hide();
		$('#addCoinButton').removeAttr("disabled");
		$('#addQuestionButton').removeAttr("disabled");
	}	
}
function editGameInfo() {
	$('.gameInfoSpan').hide();
	$('#pointsToWinInput').val(game.pointsToWin);
	$('#maxPlayersInput').val(game.maxPlayers);
	$('#changeGamePointsToWin').html('');
	$('#changeGamePointsToWin').append('<a href="#changeGamePointsToWin" onclick="saveGameInfo()">save</a>');
	$('.gameInfoInput').show();
}
function saveGameInfo() {
	game.pointsToWin = $('#pointsToWinInput').val();
	game.maxPlayers = $('#maxPlayersInput').val();
	$('#pointsToWinSpan').html(game.pointsToWin);
	$('#maxPlayersSpan').html(game.maxPlayers);
	$('.gameInfoInput').hide();
	$('#changeGamePointsToWin a').html('');
	$('#changeGamePointsToWin').append('(<a href="#changeGamePointsToWin" onclick="editGameInfo()">edit</a>)');
	$('.gameInfoSpan').show();		
}
function createGame() {
	
	parameters = {};
	for (var i in game.items) {
		if (game.items[i] != null) {
			item = game.items[i];
			if (item instanceof Question) {
				parameters['type_' + item.id] = 'QUE';
			}
			else if (item instanceof Bonus) {
				parameters['type_' + item.id] = 'BON';
				parameters['questionId_' + item.id] = item.associatedQuestion.id;
			}
			else {
				parameters['type_' + item.id] = 'COI';
			}
			parameters['itemId_' + item.id] = item.id;
			parameters['itemLatitude_' + item.id] = (item.marker.position.lat()*1000000).toFixed(0);
			parameters['itemLongitude_' + item.id] = (item.marker.position.lng()*1000000).toFixed(0);
			parameters['itemPoints_' + item.id] = item.points;
		}
	}
	parameters['city'] = game.city;
	parameters['latitude'] = (game.latitude*1000000).toFixed(0);
	parameters['longitude'] = (game.longitude*1000000).toFixed(0);
	parameters['maxPlayers'] = game.maxPlayers;
	parameters['pointsToWin'] = game.pointsToWin;
	parameters['numberOfItems'] = game.getItems().length;
	$.ajax({
		url : createURL,
		type : 'POST',
		data : parameters,
		success: parseResult
	});
}
function parseResult(data) {
	window.location = viewURL + data;
}